package com.tan.config;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;

/**
 * @description: Mybatis打印SQL的工具
 * @author: longshifu
 * @time: 2022/7/14 11:04
 */
public class MybatisPrintSqlUtils {
    private static final Logger logger = LoggerFactory.getLogger("sys-system");
    private static final Logger log = LoggerFactory.getLogger("sys-info");

    private static final ThreadLocal<String> threadLocal = new ThreadLocal<>();


    // 封装了一下sql语句，使得结果返回完整xml路径下的sql语句节点id + sql语句
    public static String getSql(Configuration configuration, BoundSql boundSql, String sqlId, long time,
                                boolean sqlBool, boolean timeBool) {
        StringBuilder str = new StringBuilder(100);
        if (timeBool) {
            str.append(sqlId);
            str.append(":");
            str.append("耗时【");
            str.append(time);
            str.append("】毫秒");
            str.append(" 【SQL】==> ");
            str.append(threadLocal.get());
        }
        if (sqlBool) {
            String sql = showSql(configuration, boundSql);
            threadLocal.set(sql);
            return "";
        }
        String msg = str.toString();
        log.info(msg);
        return msg;
    }

    /*<br>    *如果参数是String，则添加单引号， 如果是日期，则转换为时间格式器并加单引号； 对参数是null和不是null的情况作了处理<br>　　*/
    private static String getParameterValue(Object obj) {
        String value = null;
        if (obj instanceof String) {
            value = "'" + obj.toString() + "'";
        } else if (obj instanceof Date) {
            Date date = (Date) obj;
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
            value = "'" + formatter.format(date) + "'";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                //这么为空使用null处理
                value = "null";
                //value = "";
            }

        }
        return value;
    }

    // 进行？的替换
    public static String showSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();  // 获取参数
        List<ParameterMapping> parameterMappings = boundSql
                .getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");  // sql语句中多个空格都用一个空格代替
        if (!CollectionUtils.isEmpty(parameterMappings) && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry(); // 获取类型处理器注册器，类型处理器的功能是进行java类型和数据库类型的转换<br>　　　　　　　// 如果根据parameterObject.getClass(）可以找到对应的类型，则替换
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(parameterObject)));

            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);// MetaObject主要是封装了originalObject对象，提供了get和set的方法用于获取和设置originalObject的属性值,主要支持对JavaBean、Collection、Map三种类型对象的操作
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql.getAdditionalParameter(propertyName);  // 该分支是动态sql
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                    } else {
                        sql = sql.replaceFirst("\\?", "缺失");
                    }//打印出缺失，提醒该参数缺失并防止错位
                }
            }
        }
        return sql;
    }

//    public static Boolean isPrt(MappedStatement mappedStatement) throws ClassNotFoundException {
//        // 执行方法含有 SqlNotPrint 注解，则不打印日志
//        String namespace = mappedStatement.getId();
//        //获取mapper名称
//        String className = namespace.substring(0, namespace.lastIndexOf("."));
//        //获取方法名
//        String methedName = namespace.substring(namespace.lastIndexOf(".") + 1);
//        //获取当前mapper 的方法
//        Method[] ms = Class.forName(className).getMethods();
//        for (Method m : ms) {
//            if (m.getName().equals(methedName)) {
//                SqlPrint annotation = m.getAnnotation(SqlPrint.class);
//                if (annotation != null && !annotation.value()) {
//                    return true;
//                }
//            }
//        }
//        return false;
//    }

}
